package com.maple.admin.misc.menu.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.maple.admin.misc.menu.dao.IMenuDAO;
import com.maple.admin.misc.menu.dto.MenuDTO;
import com.maple.admin.misc.menu.po.MenuPO;
import com.maple.admin.misc.paging.dto.PagingParamsDTO;

/**
 * @author luoby
 *
 */
@Repository
@Transactional
public class IMenuDAOImpl implements IMenuDAO {
	@Autowired
	SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	@Override
	public List<MenuDTO> queryAllMenus() {
		// TODO Auto-generated method stub
		MenuDTO tmpDto = new MenuDTO();
		List<MenuDTO> resultList = new ArrayList<MenuDTO>();
		Session session;
		StringBuffer hql = new StringBuffer("from MenuPO m");
		try {
			session = sessionFactory.getCurrentSession();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			session = sessionFactory.openSession();
			e.printStackTrace();
		}
		Query q = session.createQuery(hql.toString()).setCacheable(true);
		List<MenuPO> tmpList = q.list();
		for(MenuPO po: tmpList){
			BeanUtils.copyProperties(po, tmpDto);
			resultList.add(tmpDto);
			tmpDto = new MenuDTO();
		}
		return resultList;
	}

	@Override
	public List<MenuDTO> queryPaginatedMenus(PagingParamsDTO paging) {
		// TODO Auto-generated method stub
		MenuDTO tmpDto = new MenuDTO();
		List<MenuDTO> resultList = new ArrayList<MenuDTO>();
		Session session;
		StringBuffer hql = new StringBuffer("from MenuPO m ");
		try {
			session = sessionFactory.getCurrentSession();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			session = sessionFactory.openSession();
			e.printStackTrace();
		}
		Query q = session.createQuery(hql.toString()).setCacheable(true);
		q.setFirstResult(paging.getPage());
		q.setMaxResults(paging.getRows());
		List<MenuPO> tmpList = q.list();
		for(MenuPO tmpPo : tmpList){
			BeanUtils.copyProperties(tmpPo, tmpDto);
			resultList.add(tmpDto);
			tmpDto = new MenuDTO();
		}
		return resultList;
	}
	
	
}
